package init_perform

import (
	"fmt"
	"github.com/spf13/cast"
	global2 "longmen/server/config/global"
	imsdk2 "longmen/server/internal/rpc/tencentim/imsdk"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/mysql/models/models_sports"
	"time"
)

func AddAnchorTagsFromTable() {
	global2.Log.Info("AddAnchorTagsFromTable start")
	var anchorIds []int
	global2.Live().Model(&models_main.AnchorFans{}).Distinct().Pluck("anchorid", &anchorIds)

	for _, anchorId := range anchorIds {
		userStack := attendAnchorUsers(anchorId)

		if len(userStack) > 0 {
			for _, users := range userStack {
				imsdk2.GetSdk().AddTags(users, []string{fmt.Sprintf("%d", anchorId)})
			}
		}
	}
	global2.Log.Info("AddAnchorTagsFromTable end")
}

func attendAnchorUsers(anchorId int) [][]string {
	var fans []int
	global2.Live().Model(&models_main.AnchorFans{}).Where("anchorid = ?", anchorId).Pluck("fansid", &fans)

	// 每次api最多只能加100個user tag
	times := len(fans) / 100
	if len(fans)%100 != 0 {
		times++
	}

	var userStack [][]string
	var totalUser int
	for i := 0; i < times; i++ {
		var users []string
		for j := i * 100; j < (i+1)*100 && j < len(fans); j++ {
			users = append(users, cast.ToString(fans[j]))
			totalUser++
		}
		userStack = append(userStack, users)
	}
	global2.Log.Info("add tag == anchorId : ", anchorId, " total users : ", totalUser)

	return userStack
}

func AddGameTagsFromTable() {
	global2.Log.Info("AddGameTagsFromTable start")

	matchUsers := attendMatchUsers()

	if len(matchUsers) > 0 {
		for matchId, users := range matchUsers {
			// 每次api最多只能加100個user tag
			times := len(users) / 100
			if len(users)%100 != 0 {
				times++
			}
			var totalUser int
			for i := 0; i < times; i++ {
				var tagUsers []string
				for j := i * 100; j < (i+1)*100 && j < len(users); j++ {
					tagUsers = append(tagUsers, users[j])
					totalUser++
				}
				imsdk2.GetSdk().AddTags(tagUsers, []string{fmt.Sprintf("%d", matchId)})
			}
			global2.Log.Info("add tag == matchId : ", matchId, " total users : ", totalUser)
		}
	}
	global2.Log.Info("AddGameTagsFromTable end")
}

func attendMatchUsers() map[int][]string {
	o := make([]*models_sports.MatchFavorite, 0)
	err := global2.Sport().Raw(fmt.Sprint("select f.match_id , f.user_id from db_match_favorite f join db_matches_schedule s on f.match_id = s.match_id where s.match_time > ", time.Now().Unix()+30)).
		Find(&o).
		Error
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert2(), err.Error())
	}

	var m = make(map[int][]string)
	for _, v := range o {
		m[v.MatchId] = append(m[v.MatchId], cast.ToString(v.UserId))
	}

	return m
}

func AddMatchLiveNotifyTag() {
	global2.Log.Info("AddMatchLiveNotifyTag start")

	// 0 取所有用戶數量
	var count int64
	var userModels []models_main.User
	global2.GetR().Model(userModels).Count(&count)
	global2.Log.Info("AddMatchLiveNotifyTag user count : ", count)

	addImMatchLiveNotifyTag(count)

	global2.Log.Info("AddMatchLiveNotifyTag end")
}

func addImMatchLiveNotifyTag(count int64) {
	// 1 輪詢所有user, 一次一百人
	for i := 0; i <= int(count/100); i++ {
		var usersInt []int
		global2.GetR().Model(models_main.User{}).Limit(100).Offset(i*100).Pluck("id", &usersInt)

		var users []string
		for _, userInt := range usersInt {
			users = append(users, cast.ToString(userInt))
		}

		// 2 分批加入tag
		imsdk2.GetSdk().AddTags(users, []string{imsdk2.NOTIFY_START_MATCH, imsdk2.NOTIFY_START_LIVE})

		time.Sleep(5 * time.Millisecond)
	}
}
